package global

import (
	po "fly_export/prometheus"
	"io"
	"log"
	"net/http"
	"strings"
	"time"
)

type Configure struct {
	Server Server  `mapstructure:"Server"`
	Mysql  Mysql   `mapstructure:"Mysql"`
	Alerts []Alert `mapstructure:"Alerts"`
	Times  []Times `mapstructure:"Times"`
}
type Server struct {
	ServerPort int
}
type Mysql struct {
	Dsn string
}
type Times struct {
	Url  string `mapstructure:"Url"`
	Name string `mapstructure:"Name"`
}
type Alert struct {
	Url    string `mapstructure:"Url"`
	Filter string `mapstructure:"Filter"`
	Name   string `mapstructure:"Name"`
}
type Warning interface {
	Run()
}
type Runnable interface {
	Run()
}

func Run[T Runnable](alerts []T) {
	for _, v := range alerts {
		v.Run()
	}
}
func (t Times) Run() {
	var endtime time.Time
	var elasped float64
	begintime := time.Now()
	resp, err := http.Get(t.Url)
	if err != nil {
		log.Println("请求URL失败：", t.Url, "错误：", err.Error())
		endtime = time.Now()
		elasped = float64(endtime.Sub(begintime).Nanoseconds()) / 1e6
		po.Updatetimes(GVA_ALERTLOAD2, t.Url, t.Name, http.StatusNotFound, elasped)
		return
	}
	defer resp.Body.Close()

	endtime = time.Now()
	elasped = float64(endtime.Sub(begintime).Nanoseconds()) / 1e6

	respbody, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Println("读取响应体失败：", t.Url, "错误：", err.Error())

	}

	log.Println("请求url：", t.Url, "返回值为：", string(respbody), "请求时长为:", elasped, "ms")

	// 默认别名
	if t.Name == "" {
		t.Name = t.Url
	}

	po.Updatetimes(GVA_ALERTLOAD2, t.Url, t.Name, http.StatusOK, elasped)
}

func (a Alert) Run() {
	var endtime time.Time
	var elasped float64
	begintime := time.Now()

	resp, err := http.Get(a.Url)
	if err != nil {
		log.Println("请求URL失败：", a.Url, "错误：", err.Error())
		endtime = time.Now()
		elasped = float64(endtime.Sub(begintime).Nanoseconds()) / 1e6
		po.Updatestatus(GVA_ALERTLOAD, a.Url, a.Name, 500, elasped)
		return
	}
	defer resp.Body.Close()

	respbody, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Println("错误：", err.Error())

	}

	endtime = time.Now()
	elasped = float64(endtime.Sub(begintime).Nanoseconds()) / 1e6
	log.Println("请求url：", a.Url, "返回值为：", string(respbody))

	status := 200 // 默认状态码为 200
	if !strings.Contains(string(respbody), a.Filter) && a.Filter != "" {
		status = 300 // 如果响应体不包含过滤器且过滤器不为空，则设置状态码为 300
	}

	// 默认别名
	if a.Name == "" {
		a.Name = a.Url
	}

	po.Updatestatus(GVA_ALERTLOAD, a.Url, a.Name, status, elasped)
}
